package com.bkhc.umc.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bkhc.common.annotation.ApiOperation;
import com.bkhc.common.annotation.ApiPackage;
import com.bkhc.common.annotation.AuditLog;
import com.bkhc.common.constant.RdisKeyContant;
import com.bkhc.common.enu.OperationEnum;
import com.bkhc.common.exception.CustomException;
import com.bkhc.common.util.MyBeanUtils;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.UserBean;
import com.bkhc.umc.entity.User;
import com.bkhc.umc.service.UserSerivce;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/login")
@Api("后台登录服务")
@ApiPackage(code="loginService",name="后台用户登录接口",description = "登录操作接口")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserSerivce userSerivce;

    @ApiOperation(code = "login", name = "登录", description = "登录", type = "common")
    @AuditLog(object = "User", operation = "登录", type = OperationEnum.tips)
    @RequestMapping(path = "/in", method = RequestMethod.GET)
    public ResultJson<?> login(@RequestParam(name = "username") String username, @RequestParam(name = "password") String password) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Authentication authentication = null;
        try {
            authentication = authenticate(username, password);
        } catch (DisabledException | BadCredentialsException | CustomException e) {
            ResultJson.failure(ResultCode.LOGIN_ERROR);
        }
        if (authentication == null) {
            return ResultJson.failure(ResultCode.LOGIN_ERROR);
        }
        //存储认证信息

        SecurityContextHolder.getContext().setAuthentication(authentication);
        Object auth = authentication.getPrincipal();
        if (auth == null) {
            ResultJson.failure(ResultCode.LOGIN_ERROR);
        }
        final UserDetails userDetail = (UserDetails) auth;
        User user = userSerivce.queryByUsername(username);
        UserBean userBean = new UserBean();
        MyBeanUtils.copyProperties(user, userBean);
        HttpSession session = request.getSession();
        session.setAttribute(RdisKeyContant.USER_INFO_SESSION, JSONObject.toJSON(userBean).toString());
//        session.setAttribute(RdisKeyContant.USER_AUTH_SESSION,userDetail);
        ResultJson resultJson = ResultJson.success();
        resultJson.setData(userBean);
        return resultJson;
    }

    private Authentication authenticate(String username, String password) throws CustomException {
        try {
            //该方法会去调用userDetailsService.loadUserByUsername()去验证用户名和密码，如果正确，则存储该用户名密码到“security 的 context中”
            UsernamePasswordAuthenticationToken s = new UsernamePasswordAuthenticationToken(username, password);
            return authenticationManager.authenticate(s);
        } catch (DisabledException | BadCredentialsException e) {
            throw new CustomException(ResultJson.failure(ResultCode.LOGIN_ERROR, e.getMessage()));
        }
    }

    @ApiOperation(code = "loginOut", name = "登出", description = "登录", type = "common")
    @AuditLog(object = "User", operation = "loginOut", type = OperationEnum.tips)
    @RequestMapping(path = "/out", method = RequestMethod.GET)
    public ResultJson<?> loginOut() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        session.invalidate();
        return  ResultJson.success();
    }

}

